package com.hetao.assist.service.dal.base;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hetao.assist.dal.mapper.BaseNewMapper;
import com.hetao.assist.model.base.BaseEntityImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;

/**
 * @author hetao
 */

public class BaseNewServiceImpl<T extends BaseEntityImpl, ID extends Serializable> implements BaseService<T, ID> {
    protected Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    protected BaseNewMapper<T, ID> mapper;

    /**
     * 使用缓存需要重写
     *
     * @param id
     * @return
     */
    @Override
    public T get(ID id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public int insert(T entity) {
        return mapper.insert(entity);
    }

    /**
     * 使用缓存需要重写
     *
     * @param id
     * @return
     */
    @Override
    public int delete(ID id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public int update(T entity) {
        return updateEntity(entity);
    }

    /**
     * 使用缓存需要重写
     *
     * @param entity
     * @return
     */
    protected int updateEntity(T entity) {
        return mapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public List<T> list() {
        return mapper.list(null);
    }

    @Override
    public List<T> list(T entity) {
        return mapper.list(entity);
    }

    @Override
    public Page<T> page(int pageNum, int pagSize) {
        return page(null, pageNum, pagSize, null);
    }

    @Override
    public Page<T> page(int pageNum, int pagSize, String orderBy) {
        return page(null, pageNum, pagSize, orderBy);
    }

    @Override
    public Page<T> page(T entity, int pageNum, int pagSize) {
        return page(entity, pageNum, pagSize);
    }

    @Override
    public Page<T> page(T entity, int pageNum, int pagSize, String orderBy) {
        Page<T> page = PageHelper.startPage(pageNum, pagSize);
        if (StringUtils.isNotBlank(orderBy)) {
            PageHelper.orderBy(orderBy);
        }
        List<T> content = mapper.list(entity);
        return page;
    }

    protected T limitOne(List<T> list) {
        return CollectionUtils.isNotEmpty(list)?list.get(0):null;
    }

    public T selectOne(T entity) {
        PageHelper.startPage(0, 1, false);
        return limitOne(mapper.list(entity));
    }

    @Override
    public int updateEx(T entity) {
        return entity.getId() != null ? update(entity): insert(entity);
    }

}
